import * as Mock from 'mockjs';
import type { CardItem } from '../types/cardData';
import { generateSnowflakeId } from '../utils/snowflake';

// 模拟数据存储
let mockCards: CardItem[] = [];

// 初始化模拟数据
export function initMockData() {
  // 清空现有数据
  mockCards = [];
  
  // 生成模拟数据
  const now = new Date();
  const yesterday = new Date(now);
  yesterday.setDate(now.getDate() - 1);
  
  const lastWeek = new Date(now);
  lastWeek.setDate(now.getDate() - 7);
  
  const nextWeek = new Date(now);
  nextWeek.setDate(now.getDate() + 7);
  
  // 生成10条模拟数据
  for (let i = 0; i < 10; i++) {
    const mockCard: CardItem = {
      id: generateSnowflakeId(),
      title: Mock.Random.ctitle(5, 15),
      content: Mock.Random.cparagraph(3, 7),
      markdown: Mock.Random.cparagraph(1, 3),
      tags: Mock.Random.shuffle(['工作', '学习', '会议', '项目', '任务', '生活', '备忘录']).slice(0, Mock.Random.natural(1, 3)),
      created: Mock.Random.date('yyyy-MM-dd') + 'T' + Mock.Random.time() + '.000Z',
      updated: Mock.Random.date('yyyy-MM-dd') + 'T' + Mock.Random.time() + '.000Z',
      startTime: Mock.Random.date('yyyy-MM-dd') + 'T' + Mock.Random.time() + '.000Z'
    };
    
    mockCards.push(mockCard);
  }
}

// 获取卡片列表
export async function fetchMockCards(page: number, pageSize: number): Promise<{
  items: CardItem[];
  hasMore: boolean;
  total: number;
}> {
  // 如果没有数据，先初始化
  if (mockCards.length === 0) {
    initMockData();
  }
  
  // 排序：最新创建的排在前面
  const sortedCards = [...mockCards].sort((a, b) => {
    return new Date(b.created).getTime() - new Date(a.created).getTime();
  });
  
  const startIndex = (page - 1) * pageSize;
  const endIndex = startIndex + pageSize;
  
  // 模拟网络延迟
  await new Promise(resolve => setTimeout(resolve, 200));
  
  return {
    items: sortedCards.slice(startIndex, endIndex),
    hasMore: endIndex < sortedCards.length,
    total: sortedCards.length
  };
}

// 获取单个卡片
export async function getMockCard(cardId: string): Promise<CardItem | null> {
  // 如果没有数据，先初始化
  if (mockCards.length === 0) {
    initMockData();
  }
  
  // 模拟网络延迟
  await new Promise(resolve => setTimeout(resolve, 150));
  
  return mockCards.find(card => card.id === cardId) || null;
}

// 保存卡片
export async function saveMockCard(card: Partial<CardItem>): Promise<CardItem> {
  // 如果没有数据，先初始化
  if (mockCards.length === 0) {
    initMockData();
  }
  
  // 模拟网络延迟
  await new Promise(resolve => setTimeout(resolve, 300));
  
  let savedCard: CardItem;
  
  if (card.id) {
    // 更新现有卡片
    const index = mockCards.findIndex(c => c.id === card.id);
    if (index >= 0) {
      savedCard = {
        ...mockCards[index],
        ...card,
        updated: new Date().toISOString()
      };
      mockCards[index] = savedCard;
    } else {
      // 卡片不存在，创建新卡片
      savedCard = {
        id: card.id,
        title: card.title || '无标题',
        content: card.content || '',
        markdown: card.markdown || '',
        tags: card.tags || [],
        created: card.created || new Date().toISOString(),
        updated: new Date().toISOString(),
        startTime: card.startTime || new Date().toISOString()
      };
      mockCards.push(savedCard);
    }
  } else {
    // 创建新卡片
    savedCard = {
      id: generateSnowflakeId(),
      title: card.title || '无标题',
      content: card.content || '',
      markdown: card.markdown || '',
      tags: card.tags || [],
      created: new Date().toISOString(),
      updated: new Date().toISOString(),
      startTime: card.startTime || new Date().toISOString()
    };
    mockCards.push(savedCard);
  }
  
  return savedCard;
}

// 删除卡片
export async function deleteMockCard(cardId: string): Promise<boolean> {
  // 模拟网络延迟
  await new Promise(resolve => setTimeout(resolve, 250));
  
  const index = mockCards.findIndex(card => card.id === cardId);
  if (index >= 0) {
    mockCards.splice(index, 1);
    return true;
  }
  
  return false;
}

// 批量删除卡片
export async function batchDeleteMockCards(cardIds: string[]): Promise<{ success: boolean; count: number }> {
  // 模拟网络延迟
  await new Promise(resolve => setTimeout(resolve, 400));
  
  let successCount = 0;
  
  for (const cardId of cardIds) {
    const index = mockCards.findIndex(card => card.id === cardId);
    if (index >= 0) {
      mockCards.splice(index, 1);
      successCount++;
    }
  }
  
  return {
    success: successCount > 0,
    count: successCount
  };
} 